package com.javasm.crm.service.aftersale.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.crm.domin.criteria.aftesale.RefacOutApplyCriteria;
import com.javasm.crm.domin.entity.aftersale.RefacOutApply;
import com.javasm.crm.domin.entity.aftersale.RefacOutGoods;
import com.javasm.crm.domin.entity.repository.Defective;
import com.javasm.crm.domin.vo.aftersale.RefacOutApplyVO;
import com.javasm.crm.mapper.aftersale.RefacOutApplyMapper;
import com.javasm.crm.service.aftersale.IOutorderService;
import com.javasm.crm.service.aftersale.IRefacOutApplyService;
import com.javasm.crm.service.aftersale.IRefacOutGoodsService;
import com.javasm.crm.service.repository.IDefectiveService;
import com.javasm.crm.utils.transfer.DefecOutGoodsTransfer;
import com.javasm.crm.utils.transfer.RefacOutApplyTransfer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lirui
 * @since 2021-07-11
 */
@Service
@Transactional
public class RefacOutapplyServiceImpl extends ServiceImpl<RefacOutApplyMapper, RefacOutApply> implements IRefacOutApplyService {

    @Resource
    private RefacOutApplyTransfer transfer;

    @Resource
    private IDefectiveService defectiveService;

    @Resource
    private IRefacOutGoodsService outGoodsService;

    @Resource
    private DefecOutGoodsTransfer defecOutGoodsTransfer;

    @Resource
    private IOutorderService outorderService;

    @Override
    public Page<RefacOutApply> getPage(RefacOutApplyCriteria criteria) {
        //分页信息
        Integer currentPage = criteria.getCurrentPage();
        Integer pageSize = criteria.getPageSize();

        //条件查询构造器
        QueryWrapper<RefacOutApply> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RefacOutApply> lambda = wrapper.lambda();

        //创建起止时间
        LocalDateTime startTime = criteria.getStartTime();
        LocalDateTime endTime = criteria.getEndTime();

        if (startTime != null && endTime != null) {
            lambda.between(RefacOutApply::getCreateTime, startTime, endTime);
        }

        //审批起止时间
        LocalDateTime appStartTime = criteria.getAppStartTime();
        LocalDateTime appEndTime = criteria.getAppEndTime();

        if (appStartTime != null && appEndTime != null) {
            lambda.between(RefacOutApply::getApproverTime, appStartTime, appEndTime);
        }

        //返厂出库单号
        String odoCode = criteria.getOdoCode();
        if (odoCode != null && !"".equals(odoCode)) {
            lambda.like(RefacOutApply::getOdoCode, odoCode);
        }

        //返厂出库标志
        Integer status = criteria.getStatus();
        if (status != null) {
            lambda.eq(RefacOutApply::getStatus, status);
        }

        //审核状态
        Integer approveStatus = criteria.getApproveStatus();
        if (approveStatus != null) {
            lambda.eq(RefacOutApply::getApproveStatus, approveStatus);
        }

        //审核人
        String approver = criteria.getApprover();
        if (approver != null && !"".equals(approver)) {
            lambda.like(RefacOutApply::getApprover, approver);
        }

        //制单人
        String createBy = criteria.getCreateBy();
        if (createBy != null && !"".equals(createBy)) {
            lambda.like(RefacOutApply::getCreateBy, createBy);
        }

        lambda.orderByAsc(RefacOutApply::getApproveStatus);

        //分页查询
        Page<RefacOutApply> page = new Page<>(currentPage, pageSize);

        page(page, wrapper);

        return page;
    }

    @Override
    public boolean saveNewOutApply(RefacOutApplyVO refacOutApplyVO) {

        LocalDateTime now = LocalDateTime.now();
        RefacOutApply refacOutApply = transfer.toEntity(refacOutApplyVO);

        refacOutApply.setApproveStatus(1);//1 未审核
        refacOutApply.setStatus(0);
        refacOutApply.setCreateTime(now);
        //保存
        boolean save = save(refacOutApply);

        if (!save) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        //更新编码
        String s = UUID.randomUUID().toString().substring(0, 5);
        Long odoId = refacOutApply.getId();
        String odoCode = s + odoId;

        refacOutApply.setOdoCode(odoCode);

        boolean update = updateById(refacOutApply);
//
//        if (!update) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        List<Integer> idList = refacOutApplyVO.getIdList();

        //从残次品库中获取选中的商品


        if (idList.size() != 0) {

            List<Defective> defectives = defectiveService.listByIds(idList);

            //更新残次品库中的商品状态，改为1(在表中)
            for (Defective defective : defectives) {
                defective.setGoodStatus(1);
                boolean updateById = defectiveService.updateById(defective);
//                if (!updateById) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return false;
//                }
            }

            //类型转换
            List<RefacOutGoods> refacOutGoods = defecOutGoodsTransfer.toEntity(defectives);

            //设置出库申请表中商品的属性
            for (RefacOutGoods good : refacOutGoods) {
                good.setOdoId(Integer.valueOf(odoId.toString()));//对应的出库申请表id
                good.setOdoCode(odoCode);//对应的出口库申请表编号
                good.setStatus(0);//出库状态
                good.setCreateTime(now);//创建时间
            }

            //批量插入从出库申请表商品
            boolean saveBatch = outGoodsService.saveBatch(refacOutGoods);

            if (!saveBatch) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }

        return true;
    }

    @Override
    public boolean alterOutApply(RefacOutApplyVO refacOutApplyVO) {

        //根据申请单id，获得申请单对应的商品单，获得商品id，并将商品单内对应的物品设置为删除。
        Long odoId = refacOutApplyVO.getId();

        QueryWrapper<RefacOutGoods> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RefacOutGoods> lambda = wrapper.lambda();

        lambda.select(RefacOutGoods::getGoodImei).eq(RefacOutGoods::getOdoId, odoId);

        List<Object> imeiList = outGoodsService.listObjs(wrapper);

        //更改残次品库中对应商品的状态。goodStatus = 0 （在库中）
        if (imeiList.size() != 0) {

            boolean remove = outGoodsService.remove(wrapper);

            if (!remove) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }

            QueryWrapper<Defective> defectiveQueryWrapper = new QueryWrapper<>();
            LambdaQueryWrapper<Defective> defectiveLambdaQueryWrapper = defectiveQueryWrapper.lambda();

            defectiveLambdaQueryWrapper.in(Defective::getGoodImei, imeiList);

            List<Defective> defectives = defectiveService.list(defectiveQueryWrapper);

            for (Defective defective : defectives) {
                defective.setGoodStatus(0);
            }

            boolean batchById = defectiveService.updateBatchById(defectives);

//            if (!batchById) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return false;
//            }
        }

        //将新的商品加入出库商品表中
        List<Integer> idList = refacOutApplyVO.getIdList();

        if (idList.size() == 0) {
            return true;
        }

        List<Defective> newDefectiveList = defectiveService.listByIds(idList);

        //更新残次品库中的商品状态，改为1(在表中)
        for (Defective defective : newDefectiveList) {
            defective.setGoodStatus(1);
            boolean updateById = defectiveService.updateById(defective);
//            if (!updateById) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return false;
//            }
        }

        //类型转换
        List<RefacOutGoods> refacOutGoods = defecOutGoodsTransfer.toEntity(newDefectiveList);

        String odoCode = refacOutApplyVO.getOdoCode();
        LocalDateTime now = LocalDateTime.now();

        //设置出库申请表中商品的属性
        for (RefacOutGoods good : refacOutGoods) {
            good.setOdoId(Integer.valueOf(odoId.toString()));//对应的出库申请表id
            good.setOdoCode(odoCode);//对应的出口库申请表编号
            good.setStatus(0);//出库状态
            good.setCreateTime(now);//创建时间
        }

        //批量插入从出库申请表商品
        boolean saveBatch = outGoodsService.saveBatch(refacOutGoods);

        if (!saveBatch) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        return true;
    }

    @Override
    public boolean batchDelApply(List<Serializable> idList) {

        //移除申请单对应物品单中的物品，并获得imei号
        QueryWrapper<RefacOutGoods> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RefacOutGoods> lambda = wrapper.lambda();

        lambda.select(RefacOutGoods::getGoodImei).in(RefacOutGoods::getOdoId, idList);

        List<Object> imeiList = outGoodsService.listObjs(wrapper);

        if (imeiList.size() != 0) {

            boolean remove = outGoodsService.remove(wrapper);

            if (!remove) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }

            //更新残品库，将残品库中对应商品的状态改为在库中
            UpdateWrapper<Defective> updateWrapper = new UpdateWrapper<>();

            updateWrapper.in("good_imei", imeiList);

            updateWrapper.set("good_status", 0);

            boolean update = defectiveService.update(updateWrapper);

//            if (!update) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return false;
//            }
        }

        //删除申请单
        boolean removeByIds = removeByIds(idList);

        if (!removeByIds) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    public boolean approveApply(RefacOutApply refacOutApply, String approver) {

        //更新出库申请单
        Long id = refacOutApply.getId();

        Integer approveStatus = refacOutApply.getApproveStatus();

        String approverComments = refacOutApply.getApproverComments();

        LocalDateTime now = LocalDateTime.now();

        UpdateWrapper<RefacOutApply> updateWrapper = new UpdateWrapper<>();

        updateWrapper.eq("id", id)
                .set("approve_status", approveStatus)
                .set("approver_comments", approverComments)
                .set("approver_time", now)
                .set("approver", approver);

        boolean update = update(updateWrapper);

//        if (!update) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        //审核通过，调用生成出库订单方法，更改仓库中对应商品的状态
        if (approveStatus == 2) {
            boolean newOutOrder = outorderService.generateNewOutOrder(refacOutApply);
            if (!newOutOrder) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }


            //获得串码的集合
            QueryWrapper<RefacOutGoods> wrapper = new QueryWrapper<>();
            LambdaQueryWrapper<RefacOutGoods> outGoodsLambdaQueryWrapper = wrapper.lambda();

            outGoodsLambdaQueryWrapper.select(RefacOutGoods::getGoodImei).eq(RefacOutGoods::getOdoId, refacOutApply.getId());

            List<Object> imeiList = outGoodsService.listObjs(wrapper);


            //根据串码，修改残次品库中的商品状态
            if (imeiList.size() != 0) {
                //更新出库商品单中商品状态(暂时不需要)
                UpdateWrapper<RefacOutGoods> outGoodsUpdateWrapper = new UpdateWrapper<>();
                LambdaUpdateWrapper<RefacOutGoods> lambda = outGoodsUpdateWrapper.lambda();

                lambda.eq(RefacOutGoods::getOdoId, refacOutApply.getId()).set(RefacOutGoods::getStatus, 1);

                boolean updateOutGoods = outGoodsService.update(outGoodsUpdateWrapper);

//                if (!updateOutGoods) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return false;
//                }

                UpdateWrapper<Defective> defectiveUpdateWrapper = new UpdateWrapper<>();
                LambdaUpdateWrapper<Defective> defectiveLambdaUpdateWrapper = defectiveUpdateWrapper.lambda();

                defectiveLambdaUpdateWrapper.in(Defective::getGoodImei, imeiList).set(Defective::getGoodStatus, 2);
                boolean updateDefectiv = defectiveService.update(defectiveUpdateWrapper);

//                if (!updateDefectiv) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return false;
//                }
            }
        }

        return true;
    }

}
